package com.example.daily.ui.profile

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.daily.data.dao.WeightRecordDao
import com.example.daily.data.entity.WeightRecord
import com.example.daily.data.UserPreferences
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.ZoneId
import java.util.*
import javax.inject.Inject

data class ProfileUiState(
    val weightRecords: List<WeightRecord> = emptyList(),
    val latestWeight: Float? = null,
    val isLoading: Boolean = false,
    val error: String? = null
)

@HiltViewModel
class ProfileViewModel @Inject constructor(
    private val weightRecordDao: WeightRecordDao,
    private val userPreferences: UserPreferences
) : ViewModel() {
    private val _uiState = MutableStateFlow(ProfileUiState())
    val uiState: StateFlow<ProfileUiState> = _uiState

    init {
        loadWeightRecords()
    }

    private fun loadWeightRecords() {
        viewModelScope.launch {
            try {
                _uiState.value = _uiState.value.copy(isLoading = true)
                val userId = userPreferences.getUserId().first()
                    ?: throw IllegalStateException("用户未登录")

                // 获取所有体重记录
                weightRecordDao.getAllWeightRecords(userId).collect { records ->
                    // 获取最新的体重记录
                    val latestWeight = records.maxByOrNull { it.recordDate }?.weight
                    
                    _uiState.value = _uiState.value.copy(
                        weightRecords = records.sortedByDescending { it.recordDate },
                        latestWeight = latestWeight,
                        isLoading = false
                    )
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = "加载体重记录失败: ${e.message}",
                    isLoading = false
                )
            }
        }
    }

    fun addWeightRecord(weight: Float, date: LocalDate, note: String? = null) {
        viewModelScope.launch {
            try {
                val userId = userPreferences.getUserId().first()
                    ?: throw IllegalStateException("用户未登录")

                val timestamp = date.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()
                Log.d("ProfileViewModel", "添加体重记录 - 时间戳: $timestamp (${Date(timestamp)})")

                val weightRecord = WeightRecord(
                    userId = userId,
                    weight = weight,
                    recordDate = timestamp,
                    note = note
                )
                weightRecordDao.insertWeightRecord(weightRecord)
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = "添加体重记录失败: ${e.message}"
                )
            }
        }
    }

    fun deleteWeightRecord(weightRecord: WeightRecord) {
        viewModelScope.launch {
            try {
                weightRecordDao.deleteWeightRecord(weightRecord)
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    error = "删除体重记录失败: ${e.message}"
                )
            }
        }
    }
} 